//
//  LoginViewMode.swift
//  JiaXiaoTong
//
//  Created by 沈增光 on 2018/2/24.
//  Copyright © 2018年 IT. All rights reserved.
//

import UIKit

class LoginViewMode: NSObject {
    
    var url : String?
    var params : AnyObject?
    static let shareUserLogin  = LoginViewMode()
    /// 用户登录标记
    var userLogon: Bool {
      
        // 1. 如果 token 有值，说明登录成功
        // 2. 如果没有过期，说明登录有效
        return  (self.takeOutParent() != nil) || (self.takeOutTeacher() != nil)
       // return true
    }
     var userInfoPath: String {
        
        let path = ((NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!) as NSString).appendingPathComponent("userInfoPath.archive")
        
        return  path //(path as NSString).stringByAppendingPathComponent("account.plist")
    }
    private var  YJParentsInfoPath: String {
        
    let    Path = ((NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!)as NSString).appendingPathComponent("parents.archive")
        
        return   Path  //(path as NSString).stringByAppendingPathComponent("account.plist")
    }
    private var YJSaveAnnouncementoPath: String {
        
        let   Path =
            ((NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!)as NSString).appendingPathComponent("announcement.archive")
        
        return   Path  //(path as NSString).stringByAppendingPathComponent("account.plist")
    }
    
    
}
// 登录按钮的 viewMode 网络请求
extension LoginViewMode {

    func loginUserInfo(url:String,params:Any?,sucess:@escaping ()->()){
        
        let urlString = HEADURL + url
        print(urlString,params as Any)
        TPHttpTool.sharedTools.request(method: .POST, URLString:urlString , parameters: params as AnyObject) { (results , error) in
            print(results as Any)
            if (results != nil){
                if ( (results as! [String :Any?])["msg"] as! String == "OK"){
                    let dateDictionary = results!["result"] as! [String : Any?]
                    if (self.url == "user/userLogin"){
                        let userInfo = UserInfoModel.mj_object(withKeyValues: dateDictionary as Any)
                        userInfo?.userId = (dateDictionary["id"] as! String)
                        self.saveUserInfo(userInfo: userInfo!)
                      //  NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBSwitchRootViewControllerNotification), object: nil)
                        
                    }else{
                        
                        
                        let parent  = Parents.mj_object(withKeyValues: dateDictionary)
                        self.saveParents(parents: parent!)
                        
                    }
                    self.notiWithState(state:"login")
                    sucess()
                    
                }
                
            }
            
            
            
        }
        
    }
    
}
extension LoginViewMode {
    
    func saveUserInfo (userInfo: UserInfoModel){
        
        // [NSKeyedArchiver archiveRootObject:userInfo toFile:YJUserInfoPath];
        NSKeyedArchiver.archiveRootObject(userInfo, toFile: userInfoPath)
    }
    func  saveParents(parents  : Parents){
       
         NSKeyedArchiver.archiveRootObject(parents, toFile: self.YJParentsInfoPath)
        
    }
    func  notiWithState (state: NSString) {
        
        let index  =  NSObject.tp_object(forKey: "teacherIndex") as! Int
        let noti = NSMutableDictionary()
        if index==0{
            
            let userinfo = self.UserInfoModelAction()
            noti["userId"] = userinfo?.teacher?.teacherID
            
        }else {
            
            let  parent = self.parents()
            noti["userId"] = parent?.apiStudent?.id
        }
        noti["state"] = state
        
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: kNotificationLoginOrLogOut) , object: noti)
    }
    func UserInfoModelAction()-> UserInfoModel? {
        
        let userInfo  = NSKeyedUnarchiver.unarchiveObject(withFile: self.userInfoPath)
        guard (userInfo == nil )else{
            
            return (userInfo as! UserInfoModel)
        }
        return nil
    }
    func parents ()->Parents? {
        let  par  = NSKeyedUnarchiver.unarchiveObject(withFile: YJParentsInfoPath)
        guard   ( par == nil) else{
            
            return (par as! Parents)
        }
        return nil
        
    }
    func  takeOutTeacher ()->JXTeacher? {
        
        let userInfo  = NSKeyedUnarchiver.unarchiveObject(withFile: YJUserInfoPath)
        guard (userInfo == nil ) else {
            
            
            return (userInfo as! UserInfoModel).teacher
        }
        return nil
    }
//    + (Parents *)parents
//    {
//    Parents *par = [NSKeyedUnarchiver unarchiveObjectWithFile:YJParentsInfoPath];
//    return par;
//    }
    func takeOutParent()->Parents? {
        
        let par = NSKeyedUnarchiver.unarchiveObject(withFile: self.YJParentsInfoPath)
        guard (par == nil ) else {
            
            
            return (par as! Parents)
        }
        return nil
    }
    func takeOutClassCourseList()->NSArray?{
        let userInfo = NSKeyedUnarchiver.unarchiveObject(withFile: self.userInfoPath)
        guard (userInfo == nil )else{
            
            return (userInfo as! UserInfoModel).apiClassList!
        }
        return nil
    }
    
    
}
